package com.qfedu.buy.server.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @program: NeighborBuy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-02-01 09:45
 */
public class HttpUtil {
    /**
     * 基于原生 实现get请求*/
    public static String get(String url){
        //1.实例化 资源地址对象
        try {
            URL myUrl=new URL(url);
            //2.获取连接对象
            HttpURLConnection huc= (HttpURLConnection) myUrl.openConnection();
            //3.设置连接信息
            huc.setRequestMethod("GET");
            huc.setReadTimeout(5000);
            huc.setConnectTimeout(5000);
            //4.连接
            huc.connect();
            //5.校验状态响应码
            if(huc.getResponseCode()==200){
                //6.获取网络响应
                InputStream is=huc.getInputStream();
                StringBuffer buffer=new StringBuffer();
                int len;
                byte[] data=new byte[2048];
                while ((len=is.read(data))!=-1){
                    buffer.append(new String(data,0,len));
                }
                return buffer.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 基于httpclient 的post请求*/
    public static String post(String url,String params){
        //实例化客户端对象
        HttpClient client= HttpClientBuilder.create().build();
        //实例化请求方式对象
        HttpPost post=new HttpPost(url);
        //设置请求参数信息
        StringEntity requestParams=new StringEntity(params,"UTF-8");
        post.setEntity(requestParams);
        try {
            //发起请求获取响应
            HttpResponse response=client.execute(post);
            //校验状态响应码
            if(response.getStatusLine().getStatusCode()==200){
                //获取响应内容
                return EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
